package com.shiguiwu.springmybatis.app.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiguiwu.springmybatis.app.entity.User;
import com.shiguiwu.springmybatis.app.mapper.UserMapper;
import com.shiguiwu.springmybatis.app.service.HelloService;
import com.shiguiwu.springmybatis.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

/**
 * @description:
 * @author: stone
 * @date: Created by 2021/8/4 21:55
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.app.service.Impl
 */
@Service("myUserService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private HelloService helloService;

    //内部有异常，不会回滚
    @Transactional(rollbackFor = RuntimeException.class)
    public void f() {
        CompletableFuture<Boolean> shiguieu1 = CompletableFuture.supplyAsync(() -> {
            boolean b = helloService.addUser();
            return b;
        }).exceptionally(e -> {
            e.printStackTrace();
            return false;
        });

        CompletableFuture<Void> shiguieu2 = CompletableFuture.runAsync(() -> {
            User user1 = new User();
            user1.setGender("3");
            user1.setId(24);
            this.baseMapper.updateById(user1);

        });

        Boolean aVoid = null;
        try {
            aVoid = shiguieu1.get();
            Void aVoid1 = shiguieu2.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        User user = new User();
        user.setUsername("shiguieumian1111");
        user.setPhone("18676894410");
        user.setGender("1");
        this.baseMapper.insert(user);
        if (!aVoid) {
            System.out.println(aVoid);
            throw new RuntimeException("haha11111111");
        }

        //ex();

    }

    @Override
    //@Transactional(timeout = 10)
    @Async
    public void test() {
        //连接池测试
        try {
            log.info("当前线程 ===> {}", Thread.currentThread().getName());
            //TimeUnit.MILLISECONDS.sleep(10);//秒
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.baseMapper.test();
    }

    public void ex() {
        throw new RuntimeException("haha");

    }

    @Transactional
    public void add1() {
        User user = new User();
        user.setUsername("shiguieu1");
        user.setPhone("18676894410");
        user.setGender("1");
        this.baseMapper.insert(user);
        ex();
    }


}
